/**
 * @file http_session.cpp
 * @brief HTTP会话管理的实现
 * @author AI Assistant
 * @date 2025/7/11
 * @version 1.0
 * 
 * 实现说明:
 * - 管理单个HTTP连接的完整生命周期
 * - 支持Keep-Alive长连接
 * - 集成现有的网络模块进行IO操作
 * - 提供完整的超时和错误处理
 */

#include "common/http/http_session.h"
#include <unistd.h>
#include <sys/socket.h>
#include <algorithm>

namespace common {
    namespace http {

        HttpSession::HttpSession(int fd, const common::network::InetAddress& peer_addr,
                                common::network::EventLoop* event_loop)
            : fd_(fd)
            , session_id_(fd)  // 保存原始fd作为会话ID
            , peer_addr_(peer_addr)
            , event_loop_(event_loop)
            , state_(HttpSessionState::CONNECTING)
            , bytes_to_write_(0)
            , read_timeout_ms_(30000)
            , write_timeout_ms_(30000)
            , keep_alive_timeout_ms_(60000)
            , keep_alive_enabled_(true)
            , max_keep_alive_requests_(100)
            , keep_alive_request_count_(0)
            , close_callback_called_(false) {
            
            // 创建网络通道
            channel_ = std::make_unique<common::network::Channel>(event_loop_, fd_);
            
            // 设置事件回调
            channel_->setReadCallback([this] { handleRead(); });
            channel_->setWriteCallback([this] { handleWrite(); });
            channel_->setCloseCallback([this] { handleClose(); });
            channel_->setErrorCallback([this] { handleError(); });
            
            updateIOTime();
            
            LOG_DEBUG("HttpSession created for fd: " + std::to_string(fd_) +
                    ", peer: " + peer_addr_.toIpPort());
        }

        HttpSession::~HttpSession() {
            try {
                if (!isClosed()) {
                    forceClose();
                }
                // 避免在析构时使用日志系统，使用标准输出
                std::cout << "[HttpSession] HttpSession destroyed for fd: " << fd_ << std::endl;
            } catch (const std::exception& e) {
                std::cerr << "[HttpSession] Exception in destructor for fd " << fd_ << ": " << e.what() << std::endl;
            } catch (...) {
                std::cerr << "[HttpSession] Unknown exception in destructor for fd " << fd_ << std::endl;
            }
        }

        void HttpSession::start() {
            std::lock_guard<std::mutex> lock(session_mutex_);

            LOG_DEBUG("HttpSession::start() called for fd: " + std::to_string(fd_) +
                    ", current state: " + std::to_string(static_cast<int>(state_.load())));

            if (state_.load() != HttpSessionState::CONNECTING) {
                LOG_WARNING("Cannot start session in state: " + std::to_string(static_cast<int>(state_.load())));
                return;
            }

            setState(HttpSessionState::READING);

            LOG_DEBUG("HttpSession::start() - enabling reading for fd: " + std::to_string(fd_));
            channel_->enableReading();

            // 验证 Channel 是否正确设置了事件
            LOG_DEBUG("HttpSession::start() - channel events after enableReading: " + std::to_string(channel_->events()));
            LOG_DEBUG("HttpSession::start() - channel isReading: " + std::string(channel_->isReading() ? "true" : "false"));

            updateIOTime();

            LOG_DEBUG("HttpSession started successfully for fd: " + std::to_string(fd_));
        }

        void HttpSession::close() {
            LOG_DEBUG("close() 被调用: session_id=" + std::to_string(session_id_) + ", fd=" + std::to_string(fd_));

            // 检查是否在EventLoop线程中
            if (event_loop_ && !event_loop_->isInLoopThread()) {
                LOG_DEBUG("不在EventLoop线程中，调度到EventLoop: session_id=" + std::to_string(session_id_));
                // 如果不在EventLoop线程中，使用runInLoop确保线程安全
                auto self = shared_from_this();
                event_loop_->runInLoop([self]() {
                    self->close();
                });
                return;
            }

            LOG_DEBUG("在EventLoop线程中，直接处理: session_id=" + std::to_string(session_id_));

            // 第一步：检查状态并设置为CLOSING
            bool has_pending_data = false;
            {
                std::lock_guard<std::mutex> lock(session_mutex_);

                if (isClosed()) {
                    LOG_DEBUG("会话已关闭，跳过重复关闭: session_id=" + std::to_string(session_id_));
                    return;
                }

                LOG_DEBUG("设置会话状态为CLOSING: session_id=" + std::to_string(session_id_));
                setState(HttpSessionState::CLOSING);

                // 检查是否有待发送数据
                has_pending_data = !output_buffer_.empty();
            }

            // 第二步：在锁外调用关闭回调，避免死锁
            LOG_DEBUG("准备调用关闭回调: session_id=" + std::to_string(session_id_));
            callCloseCallbackOnce();

            // 第三步：根据是否有待发送数据决定后续操作
            {
                std::lock_guard<std::mutex> lock(session_mutex_);
                if (has_pending_data) {
                    LOG_DEBUG("有待发送数据，启用写入: session_id=" + std::to_string(session_id_));
                    if (channel_) {
                        channel_->enableWriting();
                    }
                } else {
                    LOG_DEBUG("没有待发送数据，直接关闭: session_id=" + std::to_string(session_id_));
                    safeClose();
                }
            }

            LOG_DEBUG("HttpSession closing for fd: " + std::to_string(fd_) + ", session_id: " + std::to_string(session_id_));
        }

        void HttpSession::forceClose() {
            // 检查是否在EventLoop线程中
            if (event_loop_ && !event_loop_->isInLoopThread()) {
                // 如果不在EventLoop线程中，使用runInLoop确保线程安全
                auto self = shared_from_this();
                event_loop_->runInLoop([self]() {
                    self->forceClose();
                });
                return;
            }

            // 第一步：检查状态并设置为CLOSED
            {
                std::lock_guard<std::mutex> lock(session_mutex_);

                if (isClosed()) {
                    return;
                }

                setState(HttpSessionState::CLOSED);
            }

            // 第二步：在锁外调用关闭回调，避免死锁
            callCloseCallbackOnce();

            // 第三步：重新获取锁进行资源清理
            {
                std::lock_guard<std::mutex> lock(session_mutex_);
                safeClose();
            }

            LOG_DEBUG("HttpSession force closed for fd: " + std::to_string(fd_));
        }

        void HttpSession::sendResponse(const HttpResponse& response) {
            sendResponseInternal(response, true);
        }

        void HttpSession::sendResponseInternal(const HttpResponse& response, bool need_lock) {
            std::unique_lock<std::mutex> lock(session_mutex_, std::defer_lock);
            if (need_lock) {
                lock.lock();
            }

            if (!isConnected()) {
                LOG_WARNING("Cannot send response on closed session (fd: " + std::to_string(fd_) + ")");
                return;
            }

            LOG_DEBUG("Sending response: status=" + std::to_string(response.getStatus()) +
                     ", fd=" + std::to_string(fd_));

            prepareResponse(response);

            if (!output_buffer_.empty()) {
                setState(HttpSessionState::WRITING);
                channel_->enableWriting();
                updateIOTime();

                LOG_DEBUG("Response prepared and writing enabled for fd: " + std::to_string(fd_) +
                         ", buffer size: " + std::to_string(output_buffer_.size()));
            } else {
                LOG_WARNING("Response buffer is empty after preparation for fd: " + std::to_string(fd_));
            }
        }

        void HttpSession::sendResponseAsync(const HttpResponse& response, std::function<void(bool)> callback) {
            sendResponseAsyncInternal(response, callback, true);
        }

        void HttpSession::sendResponseAsyncInternal(const HttpResponse& response, std::function<void(bool)> callback, bool need_lock) {
            // 异步发送HTTP响应
            // 基于现有的事件驱动架构，使用Channel的写入事件机制

            std::unique_lock<std::mutex> lock(session_mutex_, std::defer_lock);
            if (need_lock) {
                lock.lock();
            }

            // 验证会话状态
            if (!isConnected()) {
                LOG_ERROR("Cannot send async response: session not connected (fd: " + std::to_string(fd_) + ")");
                if (callback) {
                    callback(false);
                }
                return;
            }

            // 检查当前状态是否允许发送响应
            auto current_state = state_.load();
            if (current_state != HttpSessionState::PROCESSING &&
                current_state != HttpSessionState::READING &&
                current_state != HttpSessionState::KEEP_ALIVE) {
                LOG_ERROR("Cannot send async response in current state: " + std::to_string(static_cast<int>(current_state)));
                if (callback) {
                    callback(false);
                }
                return;
            }

            try {
                // 准备响应数据
                std::string response_data = response.toString();

                // 检查响应大小
                if (response_data.size() > MAX_RESPONSE_SIZE) {
                    LOG_ERROR("Response too large: " + std::to_string(response_data.size()) + " bytes (max: " +
                             std::to_string(MAX_RESPONSE_SIZE) + ")");
                    if (callback) {
                        callback(false);
                    }
                    return;
                }

                // 创建异步写入任务
                auto write_task = std::make_shared<AsyncWriteTask>();
                write_task->session_id = fd_;
                write_task->data = std::move(response_data);
                write_task->callback = callback;
                write_task->start_time = std::chrono::steady_clock::now();

                // 将任务添加到队列
                {
                    std::lock_guard<std::mutex> write_lock(write_mutex_);
                    pending_write_tasks_.push(write_task);
                }

                // 设置状态为写入中
                setState(HttpSessionState::WRITING);

                // 如果当前没有写入任务在执行，立即开始处理
                processNextWriteTask();

                LOG_DEBUG("Async response queued for fd " + std::to_string(fd_) +
                         ", size: " + std::to_string(write_task->data.size()) + " bytes");

            } catch (const std::exception& e) {
                LOG_ERROR("Failed to queue async response for fd " + std::to_string(fd_) + ": " + std::string(e.what()));
                stats_.errors++;
                if (callback) {
                    callback(false);
                }
            }
        }

        bool HttpSession::isTimeout() const {
            auto now = std::chrono::steady_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_io_time_).count();
            
            auto state = state_.load();
            switch (state) {
                case HttpSessionState::READING:
                    return elapsed > read_timeout_ms_;
                case HttpSessionState::WRITING:
                    return elapsed > write_timeout_ms_;
                case HttpSessionState::KEEP_ALIVE:
                    return elapsed > keep_alive_timeout_ms_;
                default:
                    return false;
            }
        }

        void HttpSession::handleRead() {
            LOG_INFO("HttpSession::handleRead() called for fd: " + std::to_string(fd_) + ", session_id: " + std::to_string(session_id_));

            // 用于存储需要在锁外执行的操作
            bool should_close = false;
            bool should_handle_error = false;

            {
                std::lock_guard<std::mutex> lock(session_mutex_);

                if (!isConnected()) {
                    LOG_WARNING("HttpSession::handleRead() - session not connected for fd: " + std::to_string(fd_));
                    return;
                }

                char buffer[8192];
                ssize_t n = ::read(fd_, buffer, sizeof(buffer));

                LOG_INFO("HttpSession::handleRead() - read result: " + std::to_string(n) + " bytes from fd: " + std::to_string(fd_) + ", session_id: " + std::to_string(session_id_));

                if (n > 0) {
                    // 记录接收到的原始数据
                    std::string received_data(buffer, n);
                    LOG_INFO("HttpSession::handleRead() - received raw data: [" + received_data + "]");

                    input_buffer_.append(buffer, n);
                    stats_.bytes_received += n;
                    stats_.updateActivity();
                    updateIOTime();

                    LOG_INFO("HttpSession::handleRead() - total buffer size: " + std::to_string(input_buffer_.size()));
                    LOG_INFO("HttpSession::handleRead() - complete buffer content: [" + input_buffer_ + "]");

                    // 尝试解析HTTP请求
                    if (parseHttpRequest()) {
                        LOG_INFO("HttpSession::handleRead() - parseHttpRequest() SUCCESS, processing request");
                        setState(HttpSessionState::PROCESSING);
                        processHttpRequest();
                    } else {
                        LOG_INFO("HttpSession::handleRead() - parseHttpRequest() FAILED, waiting for more data");
                        LOG_INFO("HttpSession::handleRead() - failed buffer content: [" + input_buffer_ + "]");
                    }
                } else if (n == 0) {
                    // 客户端关闭连接 - 标记需要关闭，但在锁外执行
                    LOG_DEBUG("Client closed connection for fd: " + std::to_string(fd_));
                    should_close = true;
                } else {
                    // 读取错误
                    int error = errno;
                    if (error != EAGAIN && error != EWOULDBLOCK) {
                        LOG_ERROR("Read error for fd " + std::to_string(fd_) + ": " + std::string(strerror(error)));
                        should_handle_error = true;
                    } else {
                        LOG_DEBUG("Read would block for fd " + std::to_string(fd_) + ", errno: " + std::string(strerror(error)));
                    }
                }
            }

            // 在锁外执行可能导致递归锁的操作
            if (should_close) {
                handleClose();
            } else if (should_handle_error) {
                handleError();
            }
        }

        void HttpSession::handleWrite() {
            // 用于存储需要在锁外执行的操作
            bool should_close = false;
            bool should_handle_error = false;
            std::shared_ptr<AsyncWriteTask> completed_task;

            {
                std::lock_guard<std::mutex> lock(session_mutex_);

                if (!isConnected() || output_buffer_.empty()) {
                    return;
                }

                ssize_t n = ::write(fd_, output_buffer_.data(), output_buffer_.size());

                if (n > 0) {
                    output_buffer_.erase(0, n);
                    stats_.bytes_sent += n;
                    stats_.updateActivity();
                    updateIOTime();

                    LOG_DEBUG("Wrote " + std::to_string(n) + " bytes to fd: " + std::to_string(fd_));

                    if (output_buffer_.empty()) {
                        channel_->disableWriting();

                        LOG_DEBUG("Response sent completely for fd: " + std::to_string(fd_));

                        // 检查是否有异步写入任务完成
                        {
                            std::lock_guard<std::mutex> write_lock(write_mutex_);
                            if (current_write_task_) {
                                completed_task = current_write_task_;
                                // 清除当前任务，避免重复处理
                                current_write_task_.reset();
                            }
                        }

                        // 如果有异步任务，标记需要处理完成回调
                        if (completed_task) {
                            LOG_DEBUG("Completing async write task for fd: " + std::to_string(fd_));
                            // 异步任务完成回调将在锁外处理，但不在这里处理连接关闭
                            // 连接关闭由异步回调函数负责
                        } else {
                            // 普通同步写入完成，检查是否应该保持连接
                            if (shouldKeepAlive(current_request_, HttpResponse())) {
                                LOG_DEBUG("Keeping connection alive for fd: " + std::to_string(fd_));
                                resetForNextRequest();
                                setState(HttpSessionState::KEEP_ALIVE);
                            } else {
                                LOG_DEBUG("Closing connection after response for fd: " + std::to_string(fd_));
                                should_close = true;
                            }
                        }
                    }
                } else {
                    if (errno != EAGAIN && errno != EWOULDBLOCK) {
                        LOG_ERROR("Write error for fd " + std::to_string(fd_) + ": " + std::string(strerror(errno)));
                        should_handle_error = true;
                    }
                }
            }

            // 在锁外执行可能导致递归锁的操作
            if (completed_task) {
                // 只调用完成回调，不在这里处理连接关闭
                // 连接关闭由异步回调函数中的逻辑处理
                onAsyncWriteComplete(completed_task, true);
            } else if (should_close) {
                close();
            } else if (should_handle_error) {
                handleError();
            }
        }

        void HttpSession::handleClose() {
            LOG_DEBUG("handleClose() 被调用: session_id=" + std::to_string(session_id_) + ", fd=" + std::to_string(fd_));

            try {
                // 第一步：检查状态并设置为CLOSED
                {
                    LOG_DEBUG("尝试获取session_mutex锁: session_id=" + std::to_string(session_id_));
                    std::lock_guard<std::mutex> lock(session_mutex_);
                    LOG_DEBUG("成功获取session_mutex锁: session_id=" + std::to_string(session_id_));

                    // 检查当前状态
                    auto current_state = state_.load();
                    LOG_DEBUG("当前会话状态: " + std::to_string(static_cast<int>(current_state)) +
                            ", session_id=" + std::to_string(session_id_));

                    if (isClosed()) {
                        LOG_DEBUG("会话已关闭，跳过重复处理: session_id=" + std::to_string(session_id_));
                        return;  // 已经关闭，避免重复处理
                    }

                    LOG_DEBUG("设置会话状态为CLOSED: session_id=" + std::to_string(session_id_));
                    setState(HttpSessionState::CLOSED);

                    // 验证状态是否设置成功
                    auto new_state = state_.load();
                    LOG_DEBUG("状态设置后验证: " + std::to_string(static_cast<int>(new_state)) +
                            ", session_id=" + std::to_string(session_id_));
                }

                // 第二步：在锁外调用关闭回调，避免死锁
                LOG_INFO("准备调用关闭回调: session_id=" + std::to_string(session_id_));
                callCloseCallbackOnce();
                LOG_DEBUG("关闭回调调用完成: session_id=" + std::to_string(session_id_));

                // 第三步：重新获取锁进行资源清理
                {
                    std::lock_guard<std::mutex> lock(session_mutex_);
                    LOG_DEBUG("准备执行safeClose: session_id=" + std::to_string(session_id_));
                    safeClose();
                    LOG_DEBUG("safeClose执行完成: session_id=" + std::to_string(session_id_));
                }

                LOG_DEBUG("handleClose() 执行完成: session_id=" + std::to_string(session_id_));

            } catch (const std::exception& e) {
                LOG_ERROR("handleClose() 发生异常: " + std::string(e.what()) +
                         ", session_id=" + std::to_string(session_id_));
                // 即使发生异常，也要尝试强制关闭
                try {
                    forceClose();
                } catch (...) {
                    LOG_ERROR("forceClose() 也发生异常: session_id=" + std::to_string(session_id_));
                }
            } catch (...) {
                LOG_ERROR("handleClose() 发生未知异常: session_id=" + std::to_string(session_id_));
                // 即使发生异常，也要尝试强制关闭
                try {
                    forceClose();
                } catch (...) {
                    LOG_ERROR("forceClose() 也发生未知异常: session_id=" + std::to_string(session_id_));
                }
            }
        }

        void HttpSession::handleError() {
            stats_.errors++;
            
            std::string error_msg = "Socket error for fd " + std::to_string(fd_) + ": " + std::string(strerror(errno));
            LOG_ERROR(error_msg);
            
            if (error_callback_) {
                error_callback_(shared_from_this(), error_msg);
            }
            
            forceClose();
        }

        bool HttpSession::parseHttpRequest() {
            LOG_INFO("parseHttpRequest() - START, buffer size: " + std::to_string(input_buffer_.size()));
            LOG_INFO("parseHttpRequest() - buffer content: [" + input_buffer_ + "]");

            // 检查最小HTTP请求长度
            if (input_buffer_.size() < 16) {  // "GET / HTTP/1.1\r\n"
                LOG_INFO("parseHttpRequest() - buffer too small: " + std::to_string(input_buffer_.size()));
                return false;
            }

            // 检查是否有请求行
            size_t first_line_end = input_buffer_.find("\r\n");
            if (first_line_end == std::string::npos) {
                LOG_INFO("parseHttpRequest() - no request line end found");
                return false;
            }

            std::string request_line = input_buffer_.substr(0, first_line_end);
            LOG_INFO("parseHttpRequest() - request line: [" + request_line + "]");

            // 查找HTTP请求结束标志
            size_t header_end = input_buffer_.find("\r\n\r\n");
            if (header_end == std::string::npos) {
                // 请求头未完整接收
                LOG_INFO("parseHttpRequest() - headers incomplete, waiting for more data");
                return false;
            }

            LOG_DEBUG("parseHttpRequest() - header_end: " + std::to_string(header_end));

            // 提取完整的请求数据（包括可能的请求体）
            std::string request_data = input_buffer_.substr(0, header_end + 4);
            LOG_DEBUG("parseHttpRequest() - request_data: [" + request_data + "]");

            // 先只解析头部以获取Content-Length，不包含请求体
            std::string header_only_data = request_data;

            // 直接解析完整请求，避免重复解析
            // 先尝试解析头部以获取Content-Length
            size_t content_length = 0;

            // 简单解析Content-Length头部
            size_t cl_pos = input_buffer_.find("Content-Length:");
            if (cl_pos == std::string::npos) {
                cl_pos = input_buffer_.find("content-length:");
            }

            if (cl_pos != std::string::npos && cl_pos < header_end) {
                size_t cl_start = input_buffer_.find(":", cl_pos) + 1;
                size_t cl_end = input_buffer_.find("\r\n", cl_start);
                if (cl_end != std::string::npos) {
                    std::string cl_str = input_buffer_.substr(cl_start, cl_end - cl_start);
                    // 去除空白字符
                    cl_str.erase(0, cl_str.find_first_not_of(" \t"));
                    cl_str.erase(cl_str.find_last_not_of(" \t") + 1);
                    try {
                        content_length = std::stoull(cl_str);
                    } catch (...) {
                        content_length = 0;
                    }
                }
            }

            LOG_DEBUG("parseHttpRequest() - 解析得到content_length: " + std::to_string(content_length));

            size_t total_length = header_end + 4 + content_length;

            LOG_DEBUG("parseHttpRequest() - total_length: " + std::to_string(total_length));
            LOG_DEBUG("parseHttpRequest() - input_buffer_.length(): " + std::to_string(input_buffer_.length()));

            if (input_buffer_.length() >= total_length) {
                // 请求完整接收，解析完整的请求（只解析一次）
                std::string complete_request_data = input_buffer_.substr(0, total_length);

                if (current_request_.parseFromRawData(complete_request_data)) {
                    // 移除已处理的数据
                    input_buffer_.erase(0, total_length);
                    LOG_DEBUG("parseHttpRequest() - 解析成功，请求体: [" + current_request_.getBody() + "]");
                    return true;
                } else {
                    LOG_ERROR("parseHttpRequest() - 请求解析失败");
                }
            } else {
                LOG_DEBUG("parseHttpRequest() - 数据不完整，等待更多数据");
                LOG_DEBUG("parseHttpRequest() - 需要: " + std::to_string(total_length) + " 字节，已有: " + std::to_string(input_buffer_.length()) + " 字节");
            }

            return false;
        }

        void HttpSession::processHttpRequest() {
            LOG_DEBUG("HttpSession::processHttpRequest() called for fd: " + std::to_string(fd_));

            if (!request_handler_) {
                LOG_ERROR("No request handler set for session");
                HttpResponse response;
                response.internalServerError("No request handler configured");
                sendResponse(response);
                return;
            }

            try {
                HttpResponse response;
                LOG_DEBUG("About to call request_handler_ for fd: " + std::to_string(fd_));
                request_handler_(current_request_, response);
                LOG_DEBUG("request_handler_ completed for fd: " + std::to_string(fd_));

                stats_.requests_handled++;
                keep_alive_request_count_++;

                // 使用异步发送避免死锁问题
                LOG_DEBUG("About to call sendResponseAsync for fd: " + std::to_string(fd_));
                sendResponseAsyncInternal(response, [this](bool success) {
                    if (success) {
                        LOG_DEBUG("Async response sent successfully for fd: " + std::to_string(fd_));

                        // 检查是否应该保持连接
                        if (shouldKeepAlive(current_request_, HttpResponse())) {
                            LOG_DEBUG("Keeping connection alive for fd: " + std::to_string(fd_));
                            resetForNextRequest();
                            setState(HttpSessionState::KEEP_ALIVE);
                        } else {
                            LOG_DEBUG("Closing connection after response for fd: " + std::to_string(fd_));
                            close();
                        }
                    } else {
                        LOG_ERROR("Failed to send async response for fd: " + std::to_string(fd_));
                        stats_.errors++;
                        close();
                    }
                }, false);  // 不需要锁，因为已经在handleRead的锁内

                LOG_DEBUG("Processed request: " + current_request_.getMethodString() +
                         " " + current_request_.getPath());

            } catch (const std::exception& e) {
                LOG_ERROR("Exception processing request: " + std::string(e.what()));

                HttpResponse response;
                response.internalServerError("Request processing failed");

                // 异常情况下也使用异步发送
                sendResponseAsyncInternal(response, [this](bool success) {
                    if (!success) {
                        LOG_ERROR("Failed to send error response for fd: " + std::to_string(fd_));
                    }
                    stats_.errors++;
                    close();
                }, false);  // 不需要锁，因为已经在handleRead的锁内
            }
        }

        void HttpSession::prepareResponse(const HttpResponse& response) {
            std::string response_data = response.toString();
            output_buffer_ += response_data;
            bytes_to_write_ = output_buffer_.size();
            
            LOG_DEBUG("Prepared response: " + std::to_string(response_data.length()) + " bytes");
        }

        bool HttpSession::shouldKeepAlive(const HttpRequest& request, const HttpResponse& response) const {
            // 暂时不使用response参数，但保留以备将来扩展
            (void)response;

            // 首先检查服务器是否启用了Keep-Alive
            if (!keep_alive_enabled_) {
                LOG_DEBUG("Keep-Alive disabled by server configuration for fd: " + std::to_string(fd_));
                return false;
            }

            // 检查是否超过最大Keep-Alive请求数
            if (keep_alive_request_count_ >= max_keep_alive_requests_) {
                LOG_DEBUG("Keep-Alive request count exceeded for fd: " + std::to_string(fd_) +
                         ", count: " + std::to_string(keep_alive_request_count_) +
                         ", max: " + std::to_string(max_keep_alive_requests_));
                return false;
            }

            // 检查客户端是否支持Keep-Alive
            bool client_keep_alive = request.isKeepAlive();
            LOG_DEBUG("Client Keep-Alive support for fd: " + std::to_string(fd_) + ": " +
                     (client_keep_alive ? "true" : "false"));

            return client_keep_alive;
        }

        void HttpSession::resetForNextRequest() {
            current_request_.reset();
            // 保留input_buffer_中可能存在的下一个请求数据
            setState(HttpSessionState::READING);
            
            LOG_DEBUG("Session reset for next request, count: " + std::to_string(keep_alive_request_count_));
        }

        void HttpSession::updateIOTime() {
            last_io_time_ = std::chrono::steady_clock::now();
        }

        void HttpSession::setState(HttpSessionState new_state) {
            auto old_state = state_.exchange(new_state);
            if (old_state != new_state) {
                LOG_DEBUG("Session state changed: " + std::to_string(static_cast<int>(old_state)) + 
                         " -> " + std::to_string(static_cast<int>(new_state)));
            }
        }

        void HttpSession::triggerError(const std::string& error) {
            if (error_callback_) {
                error_callback_(shared_from_this(), error);
            }
        }

        void HttpSession::safeClose() {
            LOG_DEBUG("safeClose() 开始执行: session_id=" + std::to_string(session_id_) + ", fd=" + std::to_string(fd_));

            // 先清理异步写入任务，避免在关闭过程中继续处理写入
            cleanupWriteTasks();

            if (channel_) {
                LOG_DEBUG("Disabling all events for fd: " + std::to_string(fd_) +
                         ", current events: " + std::to_string(channel_->events()));

                channel_->disableAll();

                LOG_DEBUG("Events disabled for fd: " + std::to_string(fd_) +
                         ", isNoneEvent: " + (channel_->isNoneEvent() ? "true" : "false"));

                // 确保从EventLoop中移除Channel
                if (event_loop_) {
                    event_loop_->removeChannel(channel_.get());
                    LOG_DEBUG("Channel removed from EventLoop for fd: " + std::to_string(fd_));
                }

                // 延迟销毁Channel，避免在事件处理过程中销毁
                if (event_loop_) {
                    // 保存fd用于日志
                    int channel_fd = channel_->fd();
                    // 将Channel的销毁延迟到下一个事件循环
                    // 使用原始指针和自定义删除器来避免std::function的复制构造问题
                    common::network::Channel* channel_ptr = channel_.release();
                    // 强制使用queueInLoop确保真正延迟执行，即使在EventLoop线程中
                    event_loop_->queueInLoop([channel_ptr, channel_fd]() {
                        // 在这里手动删除Channel
                        delete channel_ptr;
                        LOG_DEBUG("Channel delayed destruction completed for fd: " + std::to_string(channel_fd));
                    });
                    LOG_DEBUG("Channel destruction scheduled for fd: " + std::to_string(channel_fd));
                } else {
                    // 如果没有事件循环，直接销毁（但这种情况下不应该有事件处理）
                    channel_.reset();
                    LOG_DEBUG("Channel destroyed immediately for fd: " + std::to_string(fd_));
                }
            }

            if (fd_ >= 0) {
                LOG_DEBUG("关闭socket fd: " + std::to_string(fd_));
                ::close(fd_);
                fd_ = -1;
                LOG_DEBUG("Socket fd已关闭并重置为-1");
            }

            LOG_DEBUG("safeClose() 执行完成: session_id=" + std::to_string(session_id_));
        }

        void HttpSession::processNextWriteTask() {
            // 处理下一个异步写入任务
            // 基于现有的Channel事件机制，复用handleWrite逻辑

            std::lock_guard<std::mutex> write_lock(write_mutex_);

            // 如果当前有任务在执行或队列为空，直接返回
            if (current_write_task_ || pending_write_tasks_.empty()) {
                return;
            }

            // 获取下一个任务
            current_write_task_ = pending_write_tasks_.front();
            pending_write_tasks_.pop();

            if (!current_write_task_) {
                return;
            }

            LOG_DEBUG("Processing async write task for fd " + std::to_string(fd_) +
                     ", data size: " + std::to_string(current_write_task_->data.size()) + " bytes");

            // 将数据添加到输出缓冲区
            output_buffer_ += current_write_task_->data;
            bytes_to_write_ = output_buffer_.size();

            // 启用写入事件，让现有的handleWrite处理实际的写入
            if (channel_) {
                channel_->enableWriting();
            }
        }

        void HttpSession::onAsyncWriteComplete(std::shared_ptr<AsyncWriteTask> task, bool success) {
            // 处理异步写入完成
            // 在现有的handleWrite完成后调用

            if (!task) {
                LOG_WARNING("onAsyncWriteComplete called with null task for fd: " + std::to_string(fd_));
                return;
            }

            try {
                // 计算写入耗时
                auto now = std::chrono::steady_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - task->start_time);

                if (success) {
                    LOG_DEBUG("Async write completed for fd " + std::to_string(task->session_id) +
                             ", size: " + std::to_string(task->data.size()) + " bytes, " +
                             "duration: " + std::to_string(duration.count()) + "ms");
                } else {
                    LOG_ERROR("Async write failed for fd " + std::to_string(task->session_id));
                    stats_.errors++;
                }

                // 执行回调（确保只调用一次）
                if (task->callback) {
                    bool expected = false;
                    if (task->callback_called.compare_exchange_strong(expected, true)) {
                        try {
                            task->callback(success);
                        } catch (const std::exception& e) {
                            LOG_ERROR("Exception in async write task callback: " + std::string(e.what()));
                        }
                    } else {
                        LOG_WARNING("Async write task callback already called for fd: " + std::to_string(fd_));
                    }
                }

                // 注意：current_write_task_ 已经在 handleWrite 中被清理了，这里不需要再次清理

                // 检查是否还有待处理的任务
                bool has_more_tasks = false;
                {
                    std::lock_guard<std::mutex> write_lock(write_mutex_);
                    has_more_tasks = !pending_write_tasks_.empty();
                }

                if (has_more_tasks) {
                    // 异步处理下一个任务，避免递归锁
                    if (event_loop_) {
                        event_loop_->runInLoop([this]() {
                            processNextWriteTask();
                        });
                    } else {
                        // 如果没有事件循环，直接处理（但要小心递归）
                        processNextWriteTask();
                    }
                } else {
                    LOG_DEBUG("No more async write tasks for fd: " + std::to_string(fd_));
                }

            } catch (const std::exception& e) {
                LOG_ERROR("Exception in async write completion handler: " + std::string(e.what()));
                if (task->callback) {
                    bool expected = false;
                    if (task->callback_called.compare_exchange_strong(expected, true)) {
                        try {
                            task->callback(false);
                        } catch (const std::exception& callback_e) {
                            LOG_ERROR("Exception in error callback: " + std::string(callback_e.what()));
                        }
                    }
                }
            }
        }

        void HttpSession::cleanupWriteTasks() {
            // 清理所有待处理的异步写入任务
            // 在会话关闭时调用

            LOG_DEBUG("cleanupWriteTasks() 开始执行: session_id=" + std::to_string(session_id_));

            std::lock_guard<std::mutex> write_lock(write_mutex_);

            LOG_DEBUG("Cleaning up async write tasks for fd " + std::to_string(fd_) +
                     ", pending tasks: " + std::to_string(pending_write_tasks_.size()));

            // 清理待处理任务
            int cleaned_pending = 0;
            while (!pending_write_tasks_.empty()) {
                auto task = pending_write_tasks_.front();
                pending_write_tasks_.pop();
                cleaned_pending++;

                if (task && task->callback) {
                    try {
                        task->callback(false);
                    } catch (const std::exception& e) {
                        LOG_ERROR("Exception in write task callback: " + std::string(e.what()));
                    }
                }
            }

            // 清理当前任务
            bool had_current_task = false;
            if (current_write_task_) {
                had_current_task = true;
                if (current_write_task_->callback) {
                    try {
                        current_write_task_->callback(false);
                    } catch (const std::exception& e) {
                        LOG_ERROR("Exception in current write task callback: " + std::string(e.what()));
                    }
                }
                current_write_task_.reset();
            }

            LOG_DEBUG("cleanupWriteTasks() 完成: session_id=" + std::to_string(session_id_) +
                    ", 清理待处理任务: " + std::to_string(cleaned_pending) +
                    ", 清理当前任务: " + (had_current_task ? "是" : "否"));
        }

        void HttpSession::callCloseCallbackOnce() {
            LOG_DEBUG("callCloseCallbackOnce() 开始执行: session_id=" + std::to_string(session_id_));

            try {
                // 使用原子操作确保回调只被调用一次
                bool expected = false;
                if (close_callback_called_.compare_exchange_strong(expected, true)) {
                    LOG_DEBUG("首次调用关闭回调: session_id=" + std::to_string(session_id_));
                    // 只有第一次调用会执行回调
                    if (close_callback_) {
                        LOG_DEBUG("调用会话关闭回调: session_id=" + std::to_string(session_id_) + ", fd=" + std::to_string(fd_));
                        try {
                            close_callback_(shared_from_this());
                            LOG_DEBUG("会话关闭回调执行成功: session_id=" + std::to_string(session_id_));
                        } catch (const std::exception& e) {
                            LOG_ERROR("会话关闭回调执行异常: " + std::string(e.what()) +
                                     ", session_id=" + std::to_string(session_id_));
                        } catch (...) {
                            LOG_ERROR("会话关闭回调执行未知异常: session_id=" + std::to_string(session_id_));
                        }
                    } else {
                        LOG_DEBUG("会话关闭回调为空: session_id=" + std::to_string(session_id_));
                    }
                } else {
                    LOG_DEBUG("会话关闭回调已被调用过: session_id=" + std::to_string(session_id_));
                }

                LOG_DEBUG("callCloseCallbackOnce() 执行完成: session_id=" + std::to_string(session_id_));

            } catch (const std::exception& e) {
                LOG_ERROR("callCloseCallbackOnce() 发生异常: " + std::string(e.what()) +
                         ", session_id=" + std::to_string(session_id_));
            } catch (...) {
                LOG_ERROR("callCloseCallbackOnce() 发生未知异常: session_id=" + std::to_string(session_id_));
            }
        }

    } // namespace http
} // namespace common
